package day26;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

//通过反射创建对象
public class Demo4 {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        //1.借助于Class对象直接创建实例
        Class c=Class.forName("day26.Person");
        //newInstance()来创建实例，底层调用无参构造方法
        Person p=(Person) c.newInstance();
        System.out.println(p);

        //2.借助于Constructor 构造方法对象，创建实例
        Constructor con=c.getDeclaredConstructor();
        Constructor con2=c.getDeclaredConstructor(String.class,Integer.class);
        //底层会运行有参和无参构造
        Person p2=(Person) con.newInstance();
        con2.setAccessible(true);
        Person p3=(Person) con2.newInstance("张三",18);
        System.out.println(p2);
        System.out.println(p3);
    }
}
